import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path/path.dart' as path_helper;
import '../models/image_file.dart';
import 'directory_access_service.dart';

class FileService {
  static Future<bool> requestPermissions() async {
    if (Platform.isAndroid) {
      final status = await Permission.storage.request();
      return status.isGranted;
    }
    return true;
  }

  static Future<String?> selectDirectory() async {
    try {
      // 在macOS上使用自定义的目录选择器以获得正确的权限
      if (Platform.isMacOS) {
        return await DirectoryAccessService.selectDirectoryWithAccess();
      } else {
        final String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
        return selectedDirectory;
      }
    } catch (e) {
      print('选择目录失败: $e');
      return null;
    }
  }

  static Future<List<MediaFile>> getMediaFromDirectory(String directoryPath) async {
    try {
      final directory = Directory(directoryPath);
      if (!await directory.exists()) return [];

      final List<FileSystemEntity> entities = await directory.list().toList();
      final List<MediaFile> mediaFiles = [];

      for (final entity in entities) {
        if (entity is File && MediaFile.isMediaFile(entity.path)) {
          final stat = await entity.stat();
          mediaFiles.add(MediaFile(
            file: entity,
            name: entity.path.split('/').last,
            path: entity.path,
            size: stat.size,
            lastModified: stat.modified,
            type: MediaFile.getMediaType(entity.path),
            extension: path_helper.extension(entity.path).toLowerCase(),
          ));
        }
      }

      mediaFiles.sort((a, b) => a.name.compareTo(b.name));
      return mediaFiles;
    } catch (e) {
      return [];
    }
  }

  static Future<List<MediaFile>> getImagesFromDirectory(String directoryPath) async {
    final mediaFiles = await getMediaFromDirectory(directoryPath);
    return mediaFiles.where((file) => file.type == MediaType.image).toList();
  }
}